<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="128px">
      <el-form-item label="维度code" prop="code">
        <el-input
            v-model="queryParams.code"
            placeholder="请输入维度code"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="维度名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入维度名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否预制" label-width="100px" prop="isDefault">
        <el-select v-model="queryParams.isDefault" style="width: 200px" clearable @keyup.enter="handleQuery">
          <el-option label="预制维度" value="0"/>
          <el-option label="非预制维度" value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item label="启用状态" prop="enable">
        <el-select v-model="queryParams.enable" style="width: 200px" clearable @keyup.enter="handleQuery">
          <el-option label="停用" value="0"/>
          <el-option label="启用" value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['keyfigure:template:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['keyfigure:template:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table class="table-container" v-loading="loading"
              stripe
              border
              :data="dimensionList"
              :show-overflow-tooltip='true'
              :header-cell-style="{'border-right':'1px solid #EEEEEE'}"
              :cell-style="{'border-right':'1px solid #EEEEEE'}"
              :row-class-name="iconHadler"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" prop="index" width="60"/>
      <el-table-column label="维度code" align="center" prop="code" v-if="columns[0].visible"/>
      <el-table-column label="维度名称" align="center" prop="name" v-if="columns[1].visible"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="是否预制" align="center" key="isDefault" prop="isDefault" v-if="columns[2].visible"
                       :show-overflow-tooltip="true">
        <template v-slot="scope">
          {{ scope.row.isDefault === '0' ? '预制维度' : '非预制维度' }}
        </template>
      </el-table-column>
      <el-table-column label="启用状态" align="center" key="enable" prop="enable" v-if="columns[3].visible"
                       :show-overflow-tooltip="true">
        <template #default="scope">
          <el-switch
              v-model="scope.row.enable"
              active-value="1"
              inactive-value="0"
              @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['template:template:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['template:template:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改参数模板对话框 -->
    <el-dialog :title="title" v-model="open" width="750px" append-to-body>
      <el-form ref="templateRef" :model="form" :inline="true" :rules="rules" label-width="100px">
        <el-form-item label="id" prop="id" v-if="false">
          <el-input v-model="form.id" placeholder="请输入维度id"/>
        </el-form-item>
        <el-form-item label="维度code" label-width="100px" prop="code">
          <el-input v-model="form.code" placeholder="请输入维度code"/>
        </el-form-item>
        <el-form-item label="维度名称" label-width="100px" prop="name">
          <el-input v-model="form.name" :min="1" placeholder="请输入维度名称"/>
        </el-form-item>

        <el-form-item label="是否启用" label-width="100px" prop="enable">
          <el-select v-model="form.enable" style="width: 200px">
            <el-option label="停用" value="0"/>
            <el-option label="启用" value="1"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Template">


const {proxy} = getCurrentInstance();


const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dictData = ref([]);
const dimensionList = ref([
      {
        "id": 1,
        "code": "DIM001",
        "name": "堆型",
        "isDefault": '0',
        "enable": '1'
      },
      {
        "id": 2,
        "code": "DIM002",
        "name": "发电功率",
        "isDefault": '0',
        "enable": '1'
      },
      {
        "id": 3,
        "code": "DIM003",
        "name": "机组寿命",
        "isDefault": '0',
        "enable": '1'
      },
      {
        "id": 4,
        "code": "DIM004",
        "name": "装机成本",
        "isDefault": '0',
        "enable": '1'
      }
    ]
);

const oldDimList = ref([
      {
        "id": 1,
        "code": "DIM001",
        "name": "堆型",
        "isDefault": '0',
        "enable": '1'
      },
      {
        "id": 2,
        "code": "DIM002",
        "name": "发电功率",
        "isDefault": '0',
        "enable": '1'
      },
      {
        "id": 3,
        "code": "DIM003",
        "name": "机组寿命",
        "isDefault": '0',
        "enable": '1'
      },
      {
        "id": 4,
        "code": "DIM004",
        "name": "装机成本",
        "isDefault": '0',
        "enable": '1'
      }
    ]
);


// 列显隐信息
const columns = ref([
  {key: 0, label: `维度code`, visible: true},
  {key: 1, label: `维度名称`, visible: true},
  {key: 2, label: '是否预制维度', visible: true},
  {key: 3, label: '是否启用', visible: true}
]);


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    code: "",
    name: "",
    isDefault: null,
    enable: null,
  },
  rules: {
    code: [{required: true, message: "维度code不能为空", trigger: "blur"}],
    name: [{required: true, message: "维度名称不能为空", trigger: "blur"}],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询参数模板列表 */
function getList() {
  // loading.value = true;
  // listTemplate(queryParams.value).then(response => {
  //   templateList.value = response.rows;
  //   total.value = response.total;
  //   loading.value = false;
  // });
  loading.value = true;
  if (queryParams.value.code || queryParams.value.name || queryParams.value.isDefault || queryParams.value.enable) {
    //按照条件过滤
    if (queryParams.value.code) {
      dimensionList.value = dimensionList.value.filter(item => item.code.indexOf(queryParams.value.code) != -1);
    }
    if (queryParams.value.name) {
      dimensionList.value = dimensionList.value.filter(item => item.name.indexOf(queryParams.value.name) != -1);
    }
    if (queryParams.value.isDefault) {
      dimensionList.value = dimensionList.value.filter(item => item.isDefault === queryParams.value.isDefault);
    }
    if (queryParams.value.enable) {
      dimensionList.value = dimensionList.value.filter(item => item.enable === queryParams.value.enable);
    }
  } else {
    dimensionList.value = oldDimList.value;
  }

  loading.value = false;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    code: null,
    name: null,
    isDefault: null,
    enable: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("templateRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  //handleQuery();
  dimensionList.value = oldDimList.value;
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加维度";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  open.value = true;
  title.value = "修改维度";
  form.value = row;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["templateRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        proxy.$modal.msgSuccess("修改成功");
        open.value = false;
        const dimension = dimensionList.value.find(item => item.id === form.value.id);
        const olddimension = oldDimList.value.find(item => item.id === form.value.id);

        //找到对应的数据进行修改
        dimension.id = form.value.id;
        dimension.code = form.value.code;
        dimension.name = form.value.name;
        dimension.enable = form.value.enable;
        dimension.isDefault = form.value.isDefault;

        //修改对应的保存数据的额值
        olddimension.id = form.value.id;
        olddimension.code = form.value.code;
        olddimension.name = form.value.name;
        olddimension.enable = form.value.enable;
        olddimension.isDefault = form.value.isDefault;

        // getList();
      } else {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        //声明一个新的维度对象
        let dim = {};
        dim.id = dimensionList.value.length + 1;
        dim.code = form.value.code;
        dim.name = form.value.name;
        dim.isDefault = "1";
        dim.enable = form.value.enable;
        dimensionList.value.push(dim);
        oldDimList.value.push(dim);
        // getList();
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  if (row.id) {
    //const _ids = row.id;
    const name = row.name;
    proxy.$modal.confirm('是否确认删除维度："' + name + '"的数据项？').then(function () {
      //return delTemplate(_ids);
      //从数组总过滤掉
      dimensionList.value = dimensionList.value.filter(item => item.id !== row.id);
    }).then(() => {
      // getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {
    });
  } else {
    proxy.$modal.confirm('是否确认删除维度："' + ids.value + '"的数据项？').then(function () {
      //return delTemplate(_ids);
      //从数组总过滤掉
      dimensionList.value = dimensionList.value.filter(item => ids.value.includes(item.id));
    }).then(() => {
      // getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {
    });
  }

}

/** 模板属性序号 */
function rowKeyfigureTemplateAttrIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}

/** 类别模板属性序号 */
function rowKeyfigureTemplateCategoryAttrIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}

/** 模板属性添加按钮操作 */
function handleAddKeyfigureTemplateAttr() {
  let obj = {};
  obj.fieldName = "";
  obj.fieldType = "";
  obj.dictId = "";
  keyfigureTemplateAttrList.value.push(obj);
  if (dictData.value.length === 0) {
    listType().then(response => {
      for (var i = 0; i < response.data.length; i++) {
        let dictObj = {};
        dictObj.value = response.data[i].dictId;
        dictObj.label = response.data[i].dictName;
        dictData.value.push(dictObj);
      }
    });
  }

}

/** 模板属性删除按钮操作 */
function handleDeleteKeyfigureTemplateAttr() {
  if (checkedKeyfigureTemplateAttr.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的模板属性数据");
  } else {
    const keyfigureTemplateAttrs = keyfigureTemplateAttrList.value;
    const checkedKeyfigureTemplateAttrs = checkedKeyfigureTemplateAttr.value;
    keyfigureTemplateAttrList.value = keyfigureTemplateAttrs.filter(function (item) {
      return checkedKeyfigureTemplateAttrs.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleKeyfigureTemplateAttrSelectionChange(selection) {
  checkedKeyfigureTemplateAttr.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('template/template/export', {
    ...queryParams.value
  }, `template_${new Date().getTime()}.xlsx`)
}

function handleStatusChange(row) {
  let text = row.enable === "0" ? "停用" : "启用";
  proxy.$modal.confirm('确认要"' + text + '""' + row.name + '"吗?').then(function () {
    //return changetemplateStatus(row.id, row.enable);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.enable = row.enable === "0" ? "1" : "0";
  });
};


function handleCategoryLevelChange() {
  // 在类别列数量发生变化时，更新表格数据
  const newRowCount = form.value.categoryLevel;
  const newData = [];
  for (var i = 0; i < newRowCount; i++) {
    let categoryData = {};
    categoryData.columnIndex = i + 1;
    categoryData.columnName = "";
    newData.push(categoryData);
  }
  keyfigureTemplateCategoryAttrList.value = newData;
}

const linkTypeId = ref(null);


//参数字段类型选中事件
function handleFieldTypeChange(row) {
  if (row.fieldType !== '4') {
    row.dictId = "";
    row.fieldValue = "";
  }
  if (row.fieldType === '7') {
    row.dictId = linkTypeId.value;
  }
}

function iconHadler({row, rowIndex}) {
  row.index = rowIndex + 1;
}

getList();
</script>

<style>
.table-container {
  height: 70vh; /* 设置容器高度为视口高度的85% */
  overflow-y: auto; /* 如果内容过多，则启用垂直滚动条 */
  position: relative; /* 为了确保滚动条在容器内部 */
}
</style>
